var config = require('./server/config')
var _  = require('lodash')
var path = require('path')
var webpack = require('webpack')
var glob = require('glob')
var ExtractTextPlugin = require('extract-text-webpack-plugin'); //css单独打包

// 跟目录
var ROOT_PATH = path.resolve(__dirname);
// 代码目录
var APP_PATH = path.resolve(ROOT_PATH, 'app');
// node模块目录
var NODE_MODULE_DIR = path.resolve(ROOT_PATH,'node_module');

// 获取指定路径下的入口文件
function getEntries(globPath) {
  var files = glob.sync(globPath),
    entries = {};

  files.forEach(function(filepath) {
    // 取倒数第二层(view下面的文件夹)做包名
    var split = filepath.split('/');
    var name = split[split.length - 2];

    entries[name] = filepath;
  });

  return entries;
}

function getEntryAndPlugin() {
  var entries = getEntries(APP_PATH + '/pages/**/index.jsx');
  var entrys = {}
  _.map(entries, (filepath, name) => {
    name = name.toLowerCase();
    // 每个页面生成一个entry，如果需要HotUpdate，在这里修改entry
    entrys[name] = filepath;
  })
  entrys["vendors"] = [// 把第三方的依赖打成一个包js包
    'babel-polyfill',
    'react',
    'react-dom',
    'react-router',
    'react-redux',
    'redux',
    'redux-thunk',
    'lodash',
    'isomorphic-fetch',
    'immutable',
    'shortid',
  ]

  var plugins = []
  plugins.push(new webpack.IgnorePlugin(/\.svg$/))
  plugins.push(new webpack.DefinePlugin({
    'process.env': {
      'NODE_ENV': JSON.stringify(config.env)
    }
  }))
  // 根据entrys里面的vendors列表,提取公共部分打成vendors.js文件
  plugins.push(new webpack.optimize.CommonsChunkPlugin('vendors', 'js/vendors.js'))
  plugins.push(new webpack.optimize.OccurenceOrderPlugin())
  plugins.push(new webpack.optimize.UglifyJsPlugin({
    compress: {
      unused: true,
      dead_code: true,
      warnings: false,
    }
  }))
  plugins.push(new webpack.NoErrorsPlugin())
  plugins.push(new ExtractTextPlugin('[name].css'))

  return { entrys, plugins }
}

var obj = getEntryAndPlugin()

var webpackConfig = {
  entry: obj.entrys,
  output:{
    path: __dirname + '/public/static/',
    filename: 'js/[name].js',
    publicPath: '/static/'
  },
  resolve: {
    extensions: ['', '.js', '.jsx', '.less', '.scss', '.css'], //后缀名自动补全
  },
  module:{
    loaders:[
      {
        test:/\.jsx?$/,
        //loaders: ['es3ify', 'babel'],   //加载babel模块
        loaders: ['babel'],   //加载babel模块
        include:APP_PATH,
        exclude:NODE_MODULE_DIR,
      },
      {
        test: /\.css$/,
        exclude: /node_modules/,
        loader: ExtractTextPlugin.extract('style', ['css', 'autoprefixer']),
        include: [APP_PATH]
      },
      {
        test: /\.less$/,
        exclude: /node_modules/,
        loader: ExtractTextPlugin.extract('style', ['css', 'autoprefixer', 'less']),
        include: [APP_PATH]
      },
      {
        test: /\.scss$/,
        exclude: /node_modules/,
        loader: ExtractTextPlugin.extract('style', ['css', 'autoprefixer', 'sass']),
        include: [APP_PATH]
      },
      {
        test: /\.(png|jpg|ico)$/,
        loader: 'url-loader?limit=8192&name=images/[name].[ext]'
      }
    ]
  },
  plugins: obj.plugins,
}

module.exports = webpackConfig
